using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class TimeManager : Singleton<TimeManager>
{
    /*
    1.空闲计时器集合
    2.工作中计时器集合
    3.更新当前工作中计时器
    4.计时器完成后放入空闲计时器
    */
    
    [SerializeField] private int initMaxTimerCount;

    private Queue<GameTimer> idleTimerQueue;
    private List<GameTimer> workingTimerList;

    protected override void Awake()
    {
        base.Awake();

        idleTimerQueue = new Queue<GameTimer>();
        workingTimerList = new List<GameTimer>();
    }

    private void Start() {
        InitTimerManager();
    }

    private void InitTimerManager()
    {
        for(int i=0; i<initMaxTimerCount; i++)
        {
            CreateTimer();
        }
    }

    private void CreateTimer()
    {
        idleTimerQueue.Enqueue(new GameTimer());
    }

    public GameTimer GetTimer(float time, Action task)
    {
        if(idleTimerQueue.Count == 0)
        {
            CreateTimer();
        }

        GameTimer timer = idleTimerQueue.Dequeue();
        timer.StartTimer(time, task);
        workingTimerList.Add(timer);

        return timer;
    }

    private void Update() {
        UpdateWorkingTimer();
    }

    private void UpdateWorkingTimer()
    {
        if(workingTimerList.Count == 0)
            return;
        
        for(int i=0; i<workingTimerList.Count; i++)
        {
            GameTimer timer = workingTimerList[i];
            
            if(timer.GetTimeState() == TimeState.Working)
            {
                timer.UpdateTimer();
            }
            else
            {
                idleTimerQueue.Enqueue(timer);
                timer.ResetTimer();
                workingTimerList.Remove(timer);
            }
        }
    }
}
